%% This function produces Figure 3 in Nucera, Sarno and Zinna "Currency Risk Premiums Redux", published on the RFS
function [matr2prt] = f_fig3(betahat, vhat, MatPrt, TypTA, MatNP, LabPrtSel, LabCSSel, LabTSSel, TypCSSel, TypTSSel, pmax, optordpc);


%% Inputs for plots PC analysis

idxprt = strmatch('prt', TypTA); % idx portfolios 
idxnp  = find(MatNP>1); % 

dataplot = betahat(idxprt, :);
nPC      = size(dataplot, 2);

NumPrtTmp = MatNP(idxnp);
LabPrtTmp = LabPrtSel;

nC = 2;   % number of columns in plot
nR = 6;   % number of raws in plot

%% Fixed Plot Options          
wmark = 50;
wlab  = 12;
wtit  = 14;
wleg  = 11;
nPC0     = 2;               % SET 2 to exclude PC1 exposures
strmark  = strvcat('s', 'd', 'c', '+', '*', 'x', '^', 'v', 'o');
LabPrtTmp = LabPrtSel;
nprt = size(LabPrtTmp, 1);
nPlim = 6;
if nprt > nPlim 
nP = 2; % if more than nPlim strategies then 2 plots 
end
nC = 2;   % number of columns in plot
nR = 3;   % number of raws in plot

%% Figure: Prt Exposures

icnt = 0; 
nstr  = size(LabPrtTmp,1);
nstr1 = nC*nR;
nstr2 = nstr - nstr1;

ipan = 0;
nstrchart = nstr1+nstr2;
nR  = 3;
nC  = 3;
figure('Name', 'FigA1')
for j = 1:nstr                        % loop over strategies

    ipan = ipan + 1;                  % subplot counter
    iprt = icnt + 1;                  % idx first portfolio strategy j
    icnt = icnt + NumPrtTmp(j);       % idx last portfolio strategy j
    iprt = iprt:icnt;                 % idx portfolios strategy j
    
    % save exposures for fake
    dataexphml(j, :) =  dataplot(iprt(end), :)-dataplot(iprt(1), :);
    datahml(:, j)    =  MatPrt(:, iprt(end))-MatPrt(:, iprt(1));
    
    subplot(nR, nC, ipan)
    for idxpc = nPC0:nPC   % loop over portfolios
        xtmp = 1:length(iprt);        % x variable (vector 1:NP) 
        ytmp = dataplot(iprt, idxpc); % exposure matrix (prt x pc)  
        nprt = length(ytmp);          % nP, number of portfolios
        scatter(xtmp,ytmp, wmark, 'k', strmark(idxpc)); hold on;
        xlim([xtmp(1)-.5 xtmp(end)+.5]) 
        
        
    end
    line([0, xtmp(end)], [0,0], 'Color', 'k', 'LineStyle', '-.') % hor line at 0
    
    % set up x-labels
    if ipan > nstrchart-nC                                       % to lable only bottom panels 
    xlab  = xlabel('Portfolios');
    set(xlab, 'FontSize', wlab, 'fontname', 'Bookman Old Style')   
    end
    
    % set up y-labels
    if mod(ipan-1,nC)==0                                       % to lable only left panels 
    ylab  = ylabel('Loadings');
    set(ylab, 'FontSize', wlab, 'fontname', 'Bookman Old Style')
    end
    
    %set up xtick labels
    strprt = strcat('P',num2str([1:nprt]'));     % x-tick strings
    set(gca, 'XTick', 1:nprt, 'XTickLabel',strprt,'FontSize',wlab, 'fontname', 'Bookman Old Style');            % set x-ticks 
    xlim([0.5 nprt+0.5])
    % set up title
    tit = title(LabPrtTmp(j, :));                           % title by strategy
    set(tit, 'FontSize', wtit, 'FontWeight', 'normal', 'fontname', 'Bookman Old Style')
    grid on 
%     axis tight
    
    if ipan == nstrchart
    strleg = strcat('F_',num2str([nPC0:nPC]'));                   % legend only for last panel
    leg    = legend(strleg,'Orientation','horizontal');
    set(leg,'FontSize', wleg, 'fontname','Bookman Old Style');
    legend boxoff   
    end
    
end % for j = 1:size(LabPrtTmp,1);

%% Figure: Prt R2s

%% - get R2s

r2matrix=zeros(size(MatPrt,2),pmax);
for i=1:size(MatPrt,2)
    for f=1:pmax
        y=MatPrt(2:end,i);     
        if optordpc == 2
            vhattmp   = vhat(:,1:f);
            vhatcheck = sum(vhattmp, 1);
            idrop     = vhatcheck == 0;
            vhattmp(:, idrop)   = [];
        else
            vhattmp = vhat(:,1:f);
        end
        x=[ones(size(y,1),1) vhattmp]; 
        idxnan=find(~isnan(sum(y,2))); % find missing values
        regr=ols(y(idxnan),x(idxnan,:));
        r2matrix(i,f)=regr.rsqr;
    end
end

matr2prt = r2matrix;

hmlr2matrix=zeros(size(datahml,2),pmax);
for i=1:size(datahml,2)
    for f=1:pmax
    y=datahml(2:end,i);
    if optordpc == 2
    vhattmp   = vhat(:,1:f);    
    vhatcheck = sum(vhattmp, 1);
    idrop     = vhatcheck == 0;
    vhattmp(:, idrop)   = []; 
    else
    vhattmp = vhat(:,1:f);
    end
    x=[ones(size(y,1),1) vhattmp]; 
    idxnan=find(~isnan(sum(y,2))); % find missing values
    regr=ols(y(idxnan),x(idxnan,:));
    hmlr2matrix(i,f)=regr.rsqr;
    end
end

matr2hml = hmlr2matrix;

%% - plot R2s

dataplot = 100*r2matrix;          % transform to % 
nPC0     = 2;                     % SET 2 to exclude PC1 exposures
icnt = 0;                         % initialize counter
nPC  = size(dataplot, 2);         % number of PCs

ipan = 0;
nstrchart = nstr1 + nstr2;
figure('Name', 'FigA2')

for j = 1:nstr                        % loop over strategies
   
    ipan = ipan + 1;                  % subplot counter
    iprt = icnt + 1;                  % idx first portfolio strategy j
    icnt = icnt + NumPrtTmp(j);       % idx last portfolio strategy j
    iprt = iprt:icnt;                 % idx portfolios strategy j
        
    subplot(nR, nC, ipan)
    if nPC0 == 1;
    ytmp = dataplot(iprt, nPC0:nPC);  % select matrix for bar plot
    ytmp(:, 2:end) = ytmp(:, 2:end)-ytmp(:, 1:end-1); % from cum R2 to R2s (as stacked cumulates) 
    elseif nPC0==2
    ytmp = dataplot(iprt, nPC0:nPC)- repmat(dataplot(iprt, 1), 1, nPC-1); % select matrix for bar plot (PC1 excluded) 
    ytmp(:, 2:end) = ytmp(:, 2:end)-ytmp(:, 1:end-1); % from cum R2 to R2s (as stacked cumulates)   
    end
    nprt = length(ytmp);
    cm = colormap(gray(5)); 
    hb=bar(ytmp,'stacked');
    for k = 1:5
    hb(k).FaceColor = cm(k,:);                       % Color Bars
    end        
        % set up x-labels
    if ipan > nstrchart-nC                                       % to label only bottom panels 
    xlab  = xlabel('Portfolios');
    set(xlab, 'FontSize', wlab, 'fontname', 'Bookman Old Style')   
    end
    
    % set up y-labels
    if mod(ipan-1,nC)==0                                       % to label only left panels 
    ylab  = ylabel('R2 (in %)');
    set(ylab, 'FontSize', wlab, 'fontname', 'Bookman Old Style')
    end
    
    %set up xtick labels
    strprt = strcat('P',num2str([1:nprt]'));     % x-tick strings
    set(gca, 'XTick', 1:nprt, 'XTickLabel',strprt,'FontSize',wlab, 'fontname', 'Bookman Old Style');            % set x-ticks 
    
    % set up title
    tit = title(LabPrtTmp(j, :));                           % title by strategy
    set(tit, 'FontSize', wtit, 'FontWeight', 'normal', 'fontname', 'Bookman Old Style')
    
    if nPC0 == 2 % add value of R2 explained 
    for jj = 1:size(ytmp, 1)
    text(jj-0.15, sum(ytmp(jj, :),2)+1, (num2str(round(dataplot(iprt(jj), nPC),0))), 'fontname', 'Bookman Old Style'); % PC1-6 R2
    end
    end
    
    ylim([0 max(sum(ytmp,2))*1.15])
    xlim([0.5 nprt+0.5])
    grid on 
  
    if ipan == nstrchart
    strleg = strcat('F_',num2str([nPC0:nPC]'));                   % legend only for last panel
    leg    = legend(strleg,'Orientation','horizontal');
    set(leg,'FontSize', wleg, 'fontname','Bookman Old Style');
    legend boxoff   
    end
    
end 

%% ************  Plot CS exposures  ******************
nPC0CS       = 2;
idxprt     = strmatch('cs', TypTA); % idx portfolios 
if not(isempty(idxprt)) == 1
dataplot   = betahat(idxprt, :);
dataplot2  = 100*r2matrix(idxprt, :); 
labplot    = LabCSSel;

else 
dataplot   = dataexphml;
dataplot2  = 100*matr2hml; 
labplot    = LabPrtSel;
TypCSSel   = 'implied';
end 

[nCS, nPC] = size(dataplot);


%% Make plot exposures   

optCSpanels = 1;

wmark = 50;
wlab  = 10;
wtit  = 14;
wleg  = 9;

if optCSpanels == 0
figure('Name', 'CS Exp (1)')
else
figure('Name', 'Fig3')
end

for j = 1:nCS
    for idxpc = nPC0:nPC              % loop over portfolios
        xtmp = 1:length(iprt);        % x variable (vector 1:NP) 
        ytmp = dataplot(j, idxpc); % exposure matrix (prt x pc)  
        if optCSpanels == 1
        subplot(1, 2, 1)
        end
        scatter(j,ytmp, wmark, 'k', strmark(idxpc),'LineWidth',1.5); hold on;      
    end   
end
line([0, nCS+.5], [0,0], 'Color', 'k', 'LineStyle', '-.') % hor line at 0
ylab  = ylabel('Loadings');
set(ylab, 'FontSize', wlab, 'fontname', 'Bookman Old Style') 
xlim([0.5 nCS+.5])
ylim([min(min(dataplot))*1.4 max(max(dataplot))*1.1])
strprt = labplot;     % x-tick strings 
set(gca, 'XTick', 1:nCS, 'XTickLabel', strprt, 'FontSize', wlab + 2, 'fontname','Bookman Old Style');            % set x-ticks 
xtickangle(45)
strleg = strcat('F_',num2str([nPC0:nPC]'));                   % legend only for last panel
leg    = legend(strleg,'Orientation','horizontal');
set(leg,'FontSize', wleg, 'fontname','Bookman Old Style');
if optCSpanels == 1                         
tit = title(strcat('Risk Exposures'));                        
set(tit, 'FontSize', wtit, 'FontWeight', 'normal', 'fontname', 'Bookman Old Style')
set(leg,'FontSize', wleg, 'fontname','Bookman Old Style');
% legend boxoff
end
grid on

%% Make plot R2s
wlab  = 10;
wtit  = 14;
wleg  = 10;
dataplot   = dataplot2; 

if optCSpanels == 0
figure('Name', 'CS R2s (1)')
end

if nPC0 == 1
    ytmp = dataplot(:, nPC0:nPC);  % select matrix for bar plot
    ytmp(:, 2:end) = ytmp(:, 2:end)-ytmp(:, 1:end-1); % from cum R2 to R2s (as stacked cumulates)
elseif nPC0==2
    ytmp = dataplot(:, nPC0:nPC)- repmat(dataplot(:, 1), 1, nPC-1); % select matrix for bar plot (PC1 excluded)
    ytmp(:, 2:end) = ytmp(:, 2:end)-ytmp(:, 1:end-1); % from cum R2 to R2s (as stacked cumulates)
end
nprt = length(ytmp);
cm = colormap(gray(5));
if optCSpanels == 1
    subplot(1, 2, 2)
end
hb=bar(ytmp,'stacked');
for k = 1:5
    hb(k).FaceColor = cm(k,:);                       % Color Bars
end
strleg = strcat('F_',num2str([nPC0:nPC]'));                   % legend only for last panel
leg    = legend(strleg,'Orientation','horizontal');
set(leg,'FontSize', wleg, 'fontname','Bookman Old Style');
if nPC0CS == 2 % add value of R2 explained 
for j = 1:nCS
text(j-0.15, sum(ytmp(j, :),2)+3, (num2str(round(dataplot(j, 1),1))),'fontname','Bookman Old Style');
end
end
ylab  = ylabel('R2 (in %)');
set(ylab, 'FontSize', wlab, 'fontname', 'Bookman Old Style'); 
xlim([0.5 nCS+.5])
ylim([-20 100])
strprt = labplot;     % x-tick strings
set(gca, 'XTick', 1:nCS, 'XTickLabel',strprt,'FontSize',wlab + 2, 'fontname','Bookman Old Style');            % set x-ticks 
xtickangle(45)
if optCSpanels == 1
tit = title(strcat('Explained Variation'));                             
set(tit, 'FontSize', wtit, 'FontWeight', 'normal', 'fontname', 'Bookman Old Style')
set(leg,'FontSize', wleg, 'fontname','Bookman Old Style');
end
% legend boxoff
grid on
set(gca,'box','off') 

%% ************  Plot TS exposures  ******************
nPC0TS       = 2;
idxprt     = strmatch('ts', TypTA); % idx portfolios 

if not(isempty(idxprt)) == 1
dataplot   = betahat(idxprt, :);
labplot    = LabTSSel;
[nTS, nPC] = size(dataplot);

%% Make plot exposures   

wmark = 50;
wlab  = 10;
wtit  = 14;
wleg  = 9;

figure('Name', 'TS Exp (1)')
for j = 1:nTS
    for idxpc = nPC0TS:nPC              % loop over portfolios
        xtmp = 1:length(iprt);        % x variable (vector 1:NP) 
        ytmp = dataplot(j, idxpc); % exposure matrix (prt x pc)  
        scatter(j,ytmp, wmark, 'k', strmark(idxpc)); hold on;      
    end   
end
ylab  = ylabel('Loadings');
set(ylab, 'FontSize', wlab, 'fontname', 'Bookman Old Style') 
xlim([0.5 nTS+.5])
strprt = labplot;     % x-tick strings
set(gca, 'XTick', 1:nTS, 'XTickLabel',strprt,'FontSize',wlab);            % set x-ticks 
xtickangle(45)
tit = title(strcat('TS Factors','(',TypTSSel,')'));  % consider making it automatic                         % title by strategy
set(tit, 'FontSize', wtit, 'FontWeight', 'normal', 'fontname', 'Bookman Old Style')
strleg = strcat('F_',num2str([nPC0:nPC]'));                   % legend only for last panel
leg    = legend(strleg,'Orientation','horizontal');
set(leg,'FontSize', wleg, 'fontname','Bookman Old Style');
legend boxoff
%% Make plot R2s

wlab  = 10;
wtit  = 14;
wleg  = 10;
dataplot   = 100*r2matrix(idxprt, :); 
figure('Name', 'TS R2s (1)')

if nPC0TS == 1
    ytmp = dataplot(:, nPC0TS:nPC);  % select matrix for bar plot
    ytmp(:, 2:end) = ytmp(:, 2:end)-ytmp(:, 1:end-1); % from cum R2 to R2s (as stacked cumulates)
elseif nPC0TS==2
    ytmp = dataplot(:, nPC0TS:nPC)- repmat(dataplot(:, 1), 1, nPC-1); % select matrix for bar plot (PC1 excluded)
    ytmp(:, 2:end) = ytmp(:, 2:end)-ytmp(:, 1:end-1); % from cum R2 to R2s (as stacked cumulates)
end
nprt = length(ytmp);
cm = colormap(parula(size(ytmp, 2)));
hb=bar(ytmp,'stacked');
for k = 1:5
    hb(k).FaceColor = cm(k,:);                       % Color Bars
end
strleg = strcat('F_',num2str([nPC0TS:nPC]'));                   % legend only for last panel
leg    = legend(strleg,'Orientation','horizontal');
set(leg,'FontSize', wleg, 'fontname','Bookman Old Style');
legend boxoff
if nPC0TS == 2 % add value of R2 explained 
for j = 1:nTS
text(j-0.15, sum(ytmp(j, :),2)+3, (num2str(round(dataplot(j, 1),1))));
end
end
ylab  = ylabel('R2 (in %)');
set(ylab, 'FontSize', wlab, 'fontname', 'Bookman Old Style'); 
xlim([0.5 nTS+.5])
ylim([0 100])
strprt = labplot;     % x-tick strings
set(gca, 'XTick', 1:nTS, 'XTickLabel',strprt,'FontSize',wlab);            % set x-ticks 
xtickangle(45)
tit = title(strcat('TS Factors','(',TypTSSel,')'));  % consider making it automatic                         % title by strategy
set(tit, 'FontSize', wtit, 'FontWeight', 'normal', 'fontname', 'Bookman Old Style')
end %if not(isempty(idxprt)) == 1